package me.leiusual.sharing.ui.order

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_order_home.*
import me.leiusual.sharing.R
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.order.adapter.OrderHomeAdapter
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-28
 * description:
 */
class OrderHomeFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val args: OrderHomeFragmentArgs by navArgs()

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_order_home, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    view_pager.adapter = OrderHomeAdapter(args.storeId, childFragmentManager)
    view_pager.currentItem = args.currentItem

    observeData()
  }

  private fun observeData() {
    mainViewModel.orderCount.observe(viewLifecycleOwner, Observer {
      Timber.v("orderCount = %s", it)
      it.entries.forEach { entry ->
        when (entry.key) {
          "PAYING_ORDER_TOTAL" -> tab_layout.getTabAt(0)?.text = "待付款(${entry.value})"
          "SENDING_ORDER_TOTAL" -> tab_layout.getTabAt(1)?.text = "待发货(${entry.value})"
          "RECEIPTING_ORDER_TOTAL" -> tab_layout.getTabAt(2)?.text = "待收货(${entry.value})"
        }
      }
    })
  }
}